//
//  UserAccountViewModel.swift
//  xinlangweibo
//
//  Created by 陈志强 on 15/11/14.
//  Copyright © 2015年 陈志强. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountViewModel: NSObject {
           //增加userAccount 属性
    var account: UserAccount?
    
    var userLogin: Bool {
        return account?.access_token != nil
    }
    
    
    var token: String? {
        return account?.access_token
    }
    
    var userName: String? {
        return account?.name
    }
    
    //用户头像 url
    var headURL: NSURL? {
        return NSURL(string: (account?.avatar_large ?? ""))
    }
    
    //在init方法中获取 用户账户
    override init() {
        account = UserAccount.loadAccount()
    }
      func loadAssesToken(code: String,finished: (error: NSError?) -> ()){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id": client_id,"client_secret":client_secret,"grant_type" : "authorization_code","code":code,"redirect_uri":redirect_uri]
        let AFN = AFHTTPRequestOperationManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            if let dict = result as? [String: AnyObject]{
                let account = UserAccount(dict:dict)
                //                print(dict)
                //                print(account)
                self.loadUserInfo(account, finished: finished)
            }
            
            }) { (_, error) -> Void in
                print(error)
        }
    }
    private func loadUserInfo(account: UserAccount,finished: (error: NSError?) -> ()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        //print(account.access_token)
        let parmaters = ["access_token": account.access_token!, "uid": account.uid!]
        
        let AFN = AFHTTPRequestOperationManager()
        AFN.GET(urlString, parameters: parmaters, success: { (_, result) -> Void in
            if let dict = result as? [String : AnyObject] {
                account.avatar_large = dict["avatar_large"] as? String
                account.name = dict["name"] as? String
                
                               account.saveAccount()
                finished(error: nil)
            }
            }) { (_, error) -> Void in
                finished(error: error)
                print(error)
        }
        
    }
}


